#include "threadtelnet.h"
#include "telnetsocket.h"

ThreadTelnet::ThreadTelnet(quint16 port,QByteArray nodeIP,qint64 subAddr,QObject *parent) :
    QThread(parent)
{
    telnetPort=port;
    telnetIP=nodeIP;
    nodeSubAddr=subAddr;
}

void ThreadTelnet::run()
{
    emit sigShowInfoToTextEdit("New Thread created. Trying to connect "+telnetIP+"...");

    telnetSocket=new TelnetSocket(telnetPort,telnetIP,nodeSubAddr);
    connect(telnetSocket,SIGNAL(sigExitThread(QByteArray,qint64)),this,SLOT(slotExitThread(QByteArray,qint64)));
    connect(telnetSocket,SIGNAL(sigTelnetConnected(QByteArray,qint64)),this,SIGNAL(sigTelnetConnected(QByteArray,qint64)));
    connect(telnetSocket,SIGNAL(sigTelnetDisconnectedTemporarily(QByteArray,qint64)),this,
            SIGNAL(sigTelnetDisconnectedTemporarily(QByteArray,qint64)));
    connect(telnetSocket,SIGNAL(sigShowInfoToTextEdit(QByteArray)),this,
            SIGNAL(sigShowInfoToTextEdit(QByteArray)));
    connect(telnetSocket,SIGNAL(sigShowInfoToErrorTextEdit(QByteArray)),this,SIGNAL(sigShowInfoToErrorTextEdit(QByteArray)));
    connect(telnetSocket,SIGNAL(sigPacketReady(QByteArray)),this,
            SIGNAL(sigPacketReady(QByteArray)));
    connect(this,SIGNAL(sigPacketToNodes(QByteArray,qint64)),telnetSocket,
            SLOT(slotPacketToNodes(QByteArray,qint64)));
    exec();
}

void ThreadTelnet::slotExitThread(QByteArray nodeIP, qint64 subAddr)
{
    if(nodeIP==telnetIP)
    {
        deleteLater();
    }
}

ThreadTelnet::~ThreadTelnet()
{
    exit(0);
    wait(500);
    if(telnetSocket->state()==QAbstractSocket::ConnectedState)
    {
        telnetSocket->disconnectFromHost();
    }
    telnetSocket->deleteLater();
    emit sigThreadDestroyed(telnetIP,nodeSubAddr);
    emit sigShowInfoToTextEdit("Thread deleted:"+telnetIP);
}
